package com.example.blackmarket.module.SecondHandTrade.ItemDetail;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.example.blackmarket.R;

import com.example.blackmarket.model.BlackMarketApi;
import com.example.blackmarket.module.Base.BaseActivity;
import com.example.blackmarket.module.Base.BaseApplication;

public class ItemDetailActivity extends BaseActivity implements ItemDetailView,View.OnClickListener {
    private TextView username;
    private TextView place;
    private TextView price;
    private WebView webView;
    private ImageView sellerImage;
    private Button submit;
    private ItemDetailPresenter itemDetailPresenter;

    private ProgressDialog progressDialog;

    //求购还是上架商品，售出为1，求购为2，售出的话按钮显示购买，求购按钮显示出售
    private int type;

    private String token;
    private  String seller_id;
    private  String buyer_id;
    private int item_id;

    @Override
    protected int getLayout() {
        return R.layout.activity_item_detail;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        token = BaseApplication.get("token",null);
        buyer_id = BaseApplication.get("studentNumber","201830662349");
        Intent intent = getIntent();
        seller_id = intent.getStringExtra("sellmanId");
        item_id = intent.getIntExtra("item_id",1);
        showData();
        initWebView();
        itemDetailPresenter = new ItemDetailPresenter(this);
    }

    private  void initWebView(){
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if(type == 1){
                    webView.loadUrl("javascript:getData(" + item_id +",'"+ token + "')");
                }else{
                    Intent intent = getIntent();
                    String name = intent.getStringExtra("item_name");
                    String description = intent.getStringExtra("description");
                    String picture = intent.getStringExtra("item_picture");
                    webView.loadUrl("javascript:buyingItem('"+name+"','"+description+"','"+picture+"')");
                }

            }
        });//防止跳到浏览器
        webView.loadUrl("file:///android_asset/sell_item_detail.html");
        webView.getSettings().setJavaScriptEnabled(true);
    }


    @Override
    public void setData(String seller_id, String buyer_id, int item_id, int type) {
        itemDetailPresenter.setData(seller_id,buyer_id,item_id,type);
    }

    @Override
    public void showSuccess() {
        progressDialog.dismiss();
        Toast toast = null;
        if(type == 1){
            toast = Toast.makeText(this,"购买成功,自动跳转中...",Toast.LENGTH_SHORT);
        }else{
            toast = Toast.makeText(this,"成功向求购者发起出售请求,自动跳转中...",Toast.LENGTH_SHORT);
        }
        toast.setGravity(Gravity.CENTER,0,0);
        toast.show();
        setResult(RESULT_OK);//暂时先告知商品列表页面数据发生了更新就行
        finish();
    }

    @Override
    public void showFailure(String message) {
        progressDialog.dismiss();
        Toast toast = null;
        toast = Toast.makeText(this, (type == 1 ? "购买" : "售出") + "失败：" + message,Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER,0,0);
        toast.show();
    }

    public void showData() {
        Intent intent = getIntent();
        //加载按钮 1是出售 2是求购
        type = intent.getIntExtra("type",1);
        submit.setText(type == 1 ? "购买" : "出售");
        //加载卖家名字、校区、价格
        username.setText(intent.getStringExtra("username"));
        int areaNum = intent.getIntExtra("areaNum",1);
        if (areaNum == 1){
            place.setText("南校");
        }else{
            place.setText("北校");
        }
        price.setText(String.format("%.2f", intent.getDoubleExtra("price",1.0)));
        //加载头像
        String sellerImageUri = intent.getStringExtra("Image");
        Glide.with(this).load(sellerImageUri).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(sellerImage);
    }

    @Override
    protected void onBindView() {
        username = findViewById(R.id.user_name);
        place = findViewById(R.id.place);
        price = findViewById(R.id.item_price);
        webView = findViewById(R.id.detail_content);
        sellerImage = findViewById(R.id.user_img);
        submit = findViewById(R.id.submit);
    }

    @Override
    protected void setButtonClick() {
        submit.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.submit: {
                alert();
                break;
            }
            default:{
                break;
                }
        }
    }

    protected void alert(){
        AlertDialog.Builder dialog = new AlertDialog.Builder(ItemDetailActivity.this);
        dialog.setTitle(type == 1 ? "确认购买？" : "确认售出？");
        dialog.setMessage("请确认您的操作");
        dialog.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                progressDialog = new ProgressDialog(ItemDetailActivity.this);
                progressDialog.setTitle("正在处理中...");
                progressDialog.setMessage("请勿离开");
                progressDialog.show();
                setData(seller_id,buyer_id,item_id,type);
            }
        });
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        dialog.show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        webView.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ViewGroup parent = findViewById(R.id.container);
        parent.removeView(webView);
        webView.destroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
        webView.onPause();
    }
}
